package com.taotao.manage.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.mapper.Mapper;
import com.taotao.common.service.RedisService;
import com.taotao.manage.pojo.Item;
import com.taotao.manage.pojo.ItemDesc;

@Service
public class ItemService extends BaseService<Item> {

	@Autowired
	private Mapper<Item> mapper;

	@Autowired
	private ItemDescService itemDescService;

	@Autowired
	private PropertiesService propertiesService;

	@Autowired
	private RedisService shardedJedisPoolService;

	/**
	 * @Description:添加商品，并添加商品描述
	 * @param item
	 * @param desc
	 * @author mingxu
	 */
	public void addItemAndDesc(Item item, String desc) {
		//添加商品
		super.save(item);

		//添加商品描述
		ItemDesc itemDesc = new ItemDesc();
		itemDesc.setItemId(item.getId());
		itemDesc.setItemDesc(desc);
		itemDescService.save(itemDesc);
	}

	/**
	 * @Description:修改商品及商品描述
	 * @param item
	 * @param desc
	 * @author mingxu
	 */
	public void updateItemAndDesc(Item item, String desc) {
		//强制设置不能修改的字段为null,如status
		item.setStatus(null);

		//修改商品
		super.updateById(item);

		//修改商品描述
		ItemDesc itemDesc = new ItemDesc();
		itemDesc.setItemId(item.getId());
		itemDesc.setItemDesc(desc);
		itemDescService.updateById(itemDesc);
	}

	/**
	 * @Description:根据id查询商品,并添加到缓存
	 * @param id
	 * @return
	 * @author mingxu
	 */
	public Item queryItemById(Long itemId) {

		//0、查看缓存中是否已经有数据，命中缓存则直接返回，没有命中则查询数据库，最后将数据存储到缓存中
		//缓存机制一定不能影响程序正常运行，所以需要捕获异常
		String str = propertiesService.REDIS_ITEM_ID;
		String key = StringUtils.replace(str, "{ID}", itemId.toString());
		try {
			//获取缓存
			String redisResult = shardedJedisPoolService.get(key);
			if (StringUtils.isNotEmpty(redisResult)) {
				//命中缓存后转换成对象返回
				return PropertiesService.MAPPER.readValue(redisResult, Item.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		//1.缓存中没有，就去数据库查询商品
		Item itemResult = mapper.selectByPrimaryKey(itemId);

		//2.将查询到的所有商品类目信息存储到缓存中

		try {
			String value = PropertiesService.MAPPER.writeValueAsString(itemResult);
			int time = Integer.parseInt(propertiesService.REDIS_ITEM_ID_TIME);
			shardedJedisPoolService.setex(key, time, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return itemResult;
	}

}
